package com.kbtd.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kbtd.dto.Result;
import com.kbtd.entity.Voucher;
import com.kbtd.entity.VoucherOrder;
import com.kbtd.mapper.VoucherMapper;
import com.kbtd.entity.SeckillVoucher;
import com.kbtd.service.ISeckillVoucherService;
import com.kbtd.service.IVoucherService;
import com.kbtd.utils.redis.RedisUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

import static com.kbtd.constant.RedisConstants.*;
import static com.kbtd.constant.SystemConstants.PROJECT_NAME;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wp
 */
@Service
public class VoucherServiceImpl extends ServiceImpl<VoucherMapper, Voucher> implements IVoucherService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Override
    public Result queryVoucherOfShop(Long shopId) {
        if (ObjectUtils.isEmpty(shopId)) {
            Result.fail("商铺id为空");
        }
        // 查询优惠券信息
        String key = RedisUtils.createKey(VOUCHER_KEY_PREFIX, shopId.toString());
        VoucherMapper mapper = getBaseMapper();
        List<Voucher> vouchers;
        String voucherStr = stringRedisTemplate.opsForValue().get(key);
        if (NULL_VALUE.equals(voucherStr)) {
            return Result.fail("优惠卷不存在！");
        } else if (voucherStr != null) {
            vouchers = JSONUtil.toList(voucherStr, Voucher.class);
        } else {
            vouchers = mapper.queryVoucherOfShop(shopId);
            String newVocherStr = JSONUtil.toJsonStr(vouchers);
            stringRedisTemplate.opsForValue().set(key, newVocherStr, VOUCHER_TTL);
        }

        // 返回结果
        return Result.ok(vouchers);
    }

    @Override
    @Transactional
    public void addSeckillVoucher(Voucher voucher) {
        // 保存优惠券
        save(voucher);
        // 保存秒杀信息
        SeckillVoucher seckillVoucher = new SeckillVoucher();
        seckillVoucher.setVoucherId(voucher.getId());
        seckillVoucher.setStock(voucher.getStock());
        seckillVoucher.setBeginTime(voucher.getBeginTime());
        seckillVoucher.setEndTime(voucher.getEndTime());
        seckillVoucherService.save(seckillVoucher);

        //添加库存缓存
        String key = RedisUtils.createKey(SECKILL_STOCK_KEY_PREFIX, voucher.getId().toString());
        Duration duration = Duration.between(LocalDateTime.now(), voucher.getEndTime());
        long ttl = duration.toMillis();
        stringRedisTemplate.opsForValue().set(key, voucher.getStock().toString(), ttl);

    }
}
